package com.sys.servlet;

import com.sys.dao.sysDao;
import com.sys.data.code;
import net.sf.json.JSONObject;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

import static com.sys.util.stringUtils.StringIsEmptyOrNull;

@WebServlet(name = "registerServlet", urlPatterns = "/sys/register", description = "注册")
public class registerServlet extends sysServlet {
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    setHeadHtml(req, resp, "registerServlet");
    sysDao dao = new sysDao();
    PrintWriter out = resp.getWriter();
    JSONObject backJson = new JSONObject();

    String username = req.getParameter("username");
    String nickName = req.getParameter("nickName");
    String password = req.getParameter("password");
    String departmentId = req.getParameter("departmentId");
    String userType = req.getParameter("userType");
    String address = req.getParameter("address");
    String sex = req.getParameter("sex");
    String age = req.getParameter("age");
    String userDuties = req.getParameter("userDuties");

    if (StringIsEmptyOrNull(username) || StringIsEmptyOrNull(password) || StringIsEmptyOrNull(nickName) || StringIsEmptyOrNull(userType)
      || StringIsEmptyOrNull(departmentId) || StringIsEmptyOrNull(address) || StringIsEmptyOrNull(sex) || StringIsEmptyOrNull(age) || StringIsEmptyOrNull(userDuties)) {
      backJson.put("code", code.ErrorParam.value());
      backJson.put("msg", code.ErrorParam.msg());
      out.print(backJson);
      return;
    }

    if (!userType.equals("0") && !userType.equals("1") && !userType.equals("2")) {
      backJson.put("code", code.ErrorParam.value());
      backJson.put("msg", code.ErrorParam.msg());
      out.print(backJson);
      return;
    }
    dao.register(username, password, nickName, departmentId, userType, address, sex, age, userDuties, out::print);
  }
}
